package com.mingyizhudao.app.view.mine;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.config.SystemConfig;
import com.dixiang.framework.http.DataHandler;
import com.dixiang.framework.network.Net;
import com.dixiang.framework.utils.AlertDialogs;
import com.dixiang.framework.utils.BitmapCache;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.common.IDataLoadListenter;
import com.mingyizhudao.app.http.DataUtils;
import com.mingyizhudao.app.moudle.bitmap.BimpTempHelper;
import com.mingyizhudao.app.moudle.bitmap.ImageGridActivity;
import com.mingyizhudao.app.moudle.bitmap.ImageItem;
import com.mingyizhudao.app.moudle.bitmap.NoScrollGridView;
import com.mingyizhudao.app.moudle.bitmap.PhotoActivity;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.ToastUtil;
import com.mingyizhudao.app.utils.UploadUtils;
import com.mingyizhudao.app.utils.UploadUtils.OnLoadListener;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.mine.bean.ImgQiNiuEntity;
import com.mingyizhudao.app.view.mine.bean.OrderItemEntity;

public class OrderDetailActivity extends MYBaseActivity{
	private OrderItemEntity orderItemEntity;
	private GridAdapter adapter;
	private Button btn_upcase;
	private Button btn_commit;
	private NoScrollGridView noScrollgridview;
	private List<ImageItem> dataChoosed = new ArrayList<ImageItem>();//选中的item
	private Handler handler = new Handler();
	private BitmapCache cache;
	private boolean isAdd = false;
	private String id ;//获取订单详情后得到的
	private String actionUrlUpImg;//获取订单详情后得到的
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_order_detail);
		super.onCreate(savedInstanceState);
		btn_upcase = (Button)findViewById(R.id.btn_upcase);
		btn_upcase.setOnClickListener(onClickListener);
		btn_commit = ((Button)findViewById(R.id.btn_commit));
		btn_commit.setOnClickListener(onClickListener);
		cache = new BitmapCache(this,Constants.PHOTOWIDTH);
		initView();
		getOrderDetail();
		
	}

	private void initView(){
		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setMessage("上传中...");

		noScrollgridview = (NoScrollGridView)findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

		adapter = new GridAdapter(this);
		noScrollgridview.setAdapter(adapter);

		noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == dataChoosed.size()) {

					Intent intent = new Intent(activity,
							ImageGridActivity.class);
					startActivityForResult(intent, 1011);
				} else {
					Intent intent = new Intent(activity,PhotoActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("dataChoosed", ( Serializable )dataChoosed);
					intent.putExtras(bundle);
					intent.putExtra("ID", arg2);
					startActivityForResult(intent, 1012);
				}
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void initHeaderView() {
		initBackView( R.drawable.left_back_white_icon, 0, new OnClickListener()
		{
			@Override
			public void onClick( View v )
			{
				finish();
			}
		} );
		setTitleViewValue(R.string.title_order_detail,0,R.color.white);
		setTopViewBg(R.color.actionbar_bg_color);
	}


	private void getOrderDetail(){
		String url = getIntent().getStringExtra(Constants.PARM_ACTION_URL);
		DataUtils.getInitial().getBookingDetail(activity, url, null, new IDataLoadListenter() {
			
			@Override
			public void onSuccess(Object result) {
				if(result != null){
					orderItemEntity = (OrderItemEntity)result;
						id = orderItemEntity.getId();
						actionUrlUpImg = orderItemEntity.getActionUrl();
						doNetGetImg();
						setOrderDetail();
				}else {
					Toast.makeText( activity, "获取数据失败！", 0 );
				}
			}
			
			@Override
			public void onError(Exception e, Object result) {
				Toast.makeText( activity, result+"", 0 );
			}
			
			@Override
			public void onCompleted(Exception e, Object result) {
				
			}
		});
	}
	
	
	
	private void setOrderDetail(){
		((TextView)findViewById(R.id.tv_order_number)).setText( orderItemEntity.getRefNo() );

		TextView tv_patient_name = (TextView)findViewById(R.id.tv_patient_name);
		tv_patient_name.setText( orderItemEntity.getPatientName() );

		//TextView tv_idcard = (TextView)findViewById(R.id.tv_idcard);
		//tv_idcard.setText( orderItemEntity. );

		TextView tv_contact_information = (TextView)findViewById(R.id.tv_contact_information);
		tv_contact_information.setText( orderItemEntity.getMobile() );
		TextView tv_hospital_name = (TextView)findViewById(R.id.tv_hospital_name);

		tv_hospital_name.setText( orderItemEntity.getHospitalName() );
		//tv_hospital_name.setText( orderItemEntity.getHpShortName() );//简称

		TextView tv_dept_name = (TextView)findViewById(R.id.tv_dept_name);
		tv_dept_name.setText( orderItemEntity.getHpDeptName() );
		TextView tv_expert_name = (TextView)findViewById(R.id.tv_expert_name);
		
		tv_expert_name.setText(  Utils.isStringEmpty(orderItemEntity.getExpertName()) ? "未填写" : orderItemEntity.getExpertName() );

		TextView tv_casename = (TextView)findViewById(R.id.tv_casename);
		tv_casename.setText( orderItemEntity.getDiseaseName() );
		TextView tv_disease_description = (TextView)findViewById(R.id.tv_disease_description);
		tv_disease_description.setText( orderItemEntity.getDiseaseDetail() );

//		List<ImageFileItem> files = orderItemEntity.getFiles();
//		if(files != null){
//			for(int i = 0; i < files.size();  i ++){
//				ImageItem item = new ImageItem();
//				item.imagePath = files.get(i).getAbsThumbnailUrl();
//				item.upImagePath = files.get(i).getAbsFileUrl();
//				dataChoosed.add(item);
//				
//			}
//			noScrollgridview.setAdapter(adapter);
//		}

		
	}

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			if (dataChoosed.size() == Constants.PHOTO_MAX_SIZE) {
				return Constants.PHOTO_MAX_SIZE;
			}
			return (dataChoosed.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		 public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.photo_ablum_item,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.blum_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position == dataChoosed.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == Constants.PHOTO_MAX_SIZE || !isAdd) {
					holder.image.setVisibility(View.GONE);
					convertView.setVisibility(View.GONE);
				}

			} else {
				if(dataChoosed.get(position).imagePath.contains("http://")){
					Net.displayImage(dataChoosed.get(position).imagePath, holder.image, R.drawable.photo_loading_image);
				}else{
					cache.displayBmp(holder.image,dataChoosed.get(position).imagePath,handler);	
				}

			}
			return convertView;
		 }

		 public class ViewHolder {
			 public ImageView image;
		 }

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if( requestCode == 1011 )
		{
			dataChoosed = BimpTempHelper.getInstance().getImageItemsChoosend();
			//			if(dataChoosed != null && dataChoosed.size() > 0){
			noScrollgridview.setAdapter(adapter);
			//			}
		}

	}

	private static final int FAIL = 500;// 更新下载进度的标记
	private static final int SUCCESS = 200;
	private ProgressDialog progressDialog;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case SUCCESS:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传成功！", 2000).show();
				finish();
				break;

			case FAIL:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传失败！", 2000).show();
				break;

			default:
				break;
			}
		}
	};
	
	//暂时不用
	/*private void uploadFile(final String id,final String requestURL){
		progressDialog.show();
		new Thread(new Runnable() {

			@Override
			public void run() {
				final Map<String, Object> params = new HashMap<String, Object>();
				params.put("bookingFile[booking_id]", id);
				params.put("bookingFile[username]", CommonUtils.getMobile(activity));
				params.put("bookingFile[token]", CommonUtils.getToken(activity));

				
				String postEncryptUrl = NetHelper.getPostEncryptUrl(requestURL);
				params.put("sign",  NetHelper.getPostSignParam(postEncryptUrl));
				
				try {
					for(int i = 0; i < dataChoosed.size(); i ++){
						Map<String, String> fileParams = new HashMap<String, String>();
						fileParams.put("bookingFile[file_data]", dataChoosed.get(i).imagePath);
						String imgPath = UploadUtil.postFile(postEncryptUrl, params, fileParams,dataChoosed.get(i).imagePath);//requestURL+"?api=5"

						if( imgPath==null )
						{
							mHandler.sendEmptyMessage(FAIL);
							return;
						}
//				        if(imgPath != null && imgPath.length() > 0){
//				        	for(int j = 0; j < dataChoosed.size() ; j ++){
////				        		if(dataChoosed.get(j).imagePath.equals(imgPath)){
////				        			dataChoosed.remove(j);
//////				        			noScrollgridview.setAdapter(new GridAdapter(activity));
//////				        			adapter.notifyDataSetChanged();
////				        			break;
////				        		}
//				        	}
//				        }
					}
					mHandler.sendEmptyMessage(SUCCESS);
				} catch (FileNotFoundException e) {
					mHandler.sendEmptyMessage(FAIL);
					e.printStackTrace();
				}
			}
		}).start();
		//		

	}*/

	
	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.btn_upcase:
				dataChoosed.clear();
				btn_commit.setVisibility(View.VISIBLE);
				isAdd = true;
				btn_upcase.setVisibility(View.GONE);
				Intent intent = new Intent(activity,
						ImageGridActivity.class);
				startActivityForResult(intent, 1011);
				break;
			case R.id.btn_commit:
//				AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
//				dlg.setOk( "提交" );
//				dlg.showAlertDialog(
//						"您已经选中了" + dataChoosed.size() + "张影像资料,确认提交！",new OnClickListener() {
//							@Override
//							public void onClick(View arg0) {
//								uploadFile(id, actionUrl);
//							}
//						});

				if (dataChoosed != null && dataChoosed.size() > 0) {
					AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
					dlg.setOk( "提交" );
					dlg.showAlertDialog(
							"您已经选中了" + dataChoosed.size() + "张影像资料,确认提交！",
							new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									//uploadFile(id, actionUrlUpImg);
									upQiniu();
								}
							});
				} else {
					AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
					dlg.setOk( "确定" );
					dlg.setContent2(true, "（可以在预约单详情界面添加）" );
					dlg.showAlertDialog(
							"您尚未上传影像资料,确定？",
							new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									//uploadFile(id, actionUrlUpImg);
								}
							});
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		BimpTempHelper.getInstance().clearData();
	}


	private void doNetGetImg() {
		
		String url = SystemConfig.APP_FILE_URL + CommonUtils.getTokenParam(activity)+"&bookingId="+id;
		
		QJNetUICallback callback = new QJNetUICallback<QjResult<HashMap<String,List<ImgQiNiuEntity>>>>(activity) {
			@Override
			public void onSuccess(QjResult<HashMap<String,List<ImgQiNiuEntity>>> result) {
				if (result != null
						&& result.getResults() != null) {
					List<ImgQiNiuEntity> list = result.getResults().get("files");
					if (list != null) {
						
						if (list.size()>=9) {
							
							btn_upcase.setVisibility(View.GONE);
						}else {
							btn_upcase.setVisibility(View.VISIBLE);
						}
						
						for(int i = 0; i < list.size();  i ++){
							ImageItem item = new ImageItem();
							item.imagePath = list.get(i).getThumbnailUrl();
							item.upImagePath = list.get(i).getAbsFileUrl();
							dataChoosed.add(item);
							noScrollgridview.setAdapter(adapter);
						}
					}
				}
			}

			public void onError(Exception e, QjResult<HashMap<String,List<ImgQiNiuEntity>>> result) {
				super.onError(e, result);
				  ToastUtil.showToast(activity, "获取失败！",Toast.LENGTH_LONG);
			}

			public void onCompleted(Exception e, QjResult<HashMap<String,List<ImgQiNiuEntity>>> result) {
				super.onCompleted(e, result);
			}
		};
		String path = new DataHandler().postDataObject(activity, url ,null, new TypeToken<QjResult<HashMap<String,List<ImgQiNiuEntity>>>>() {}, callback);
		
	}

	
	
	 private void upQiniu() {
		    progressDialog.show();
			final List<File> files = new ArrayList<File>();
			for (int i = 0; i < dataChoosed.size(); i++) {
				files.add(new File(dataChoosed.get(i).imagePath));
			}
			
			UploadUtils uploadUtils =new UploadUtils( id);
			
			uploadUtils.uploadFiles(activity, null, files, new OnLoadListener() {
				
				@Override
				public void onLoadSuccess(String remoteDomain ,String key, String str, int index) {
					doTestNet(remoteDomain ,files.get(index), index  ,key);
				}
				
				@Override
				public void onLoadSuccess(String remoteDomain ,String key, String str) {
					LoadingDialog.getInstance(activity).dismiss();
				}
				
				@Override
				public void onLoadFail() {
					progressDialog.dismiss();
					LoadingDialog.getInstance(activity).dismiss();
					Toast.makeText(activity, "上传失败！", Toast.LENGTH_LONG).show();
				}
			});
			
		}
		
	  //上传七牛成功数据保存至自己服务器
		@SuppressWarnings("unchecked")
	  	private void doTestNet(String remoteDomain ,File file ,final int index, String key) {
			LoadingDialog.getInstance(activity).show();
	  		Map map = new HashMap<String, Object>();
	  		
	  		map.put("appFile[token]", CommonUtils.getToken(activity));
	  		map.put("appFile[username]", CommonUtils.getMobile(activity));
	  		
	  		map.put("appFile[size]", file.length()/1024+"");
	  		if (file.getName().endsWith(".png")) {
	  			map.put("appFile[type]", "png");
	  		}else {
	  			map.put("appFile[type]", "jpg");
	  		}
	  		
	  		map.put("appFile[remoteDomain]", remoteDomain);
	  		map.put("appFile[remoteKey]", key);
	  		
	  		map.put("appFile[bookingId]", id);
	  		
	  		
	  		
	  		QJNetUICallback callback = new QJNetUICallback<QjResult<HashMap<String, Object>>>(activity) {
				@Override
				public void onSuccess(QjResult<HashMap<String, Object>> result) {
					if (result != null) {
							if (index+1 ==dataChoosed.size()) {
								//ToastUtil.showToast(activity, "提交自己服务器成功！",Toast.LENGTH_LONG);
								mHandler.sendEmptyMessage(SUCCESS);
						} 
						}else {
							mHandler.sendEmptyMessage(FAIL);
					}
				}

				public void onError(Exception e, QjResult<HashMap<String, Object>> result) {
					super.onError(e, result);
					  ToastUtil.showToast(activity, "提交自己服务器失败！",Toast.LENGTH_LONG);
					mHandler.sendEmptyMessage(FAIL);
				}

				public void onCompleted(Exception e, QjResult<HashMap<String, Object>> result) {
					super.onCompleted(e, result);
				}
			};
			String path = new DataHandler().postDataObject(activity, SystemConfig.SAVE_APP_FILE ,map, new TypeToken<QjResult<HashMap<String, Object>>>() {}, callback);
	  	}
}
